package com.gmako.controller;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;


import com.gmako.entity.Userinfo;
import com.gmako.service.UserinfoService;
import com.gmako.utils.MD5;
import com.gmako.utils.ResponseUtils;


@Controller
@RequestMapping("/login.do")
public class LoginController {
	@Autowired(required=false) 
	private UserinfoService userinfoService;	
	
	/**
	 * 登录
	 * @author yezhenchi
	 * @param request
	 * @return
	 */
	@RequestMapping
	public String viewLogin(HttpServletRequest request,
			HttpServletResponse response){		
		String username = request.getParameter("name");
		String pwd = request.getParameter("pwd");
		Userinfo user = userinfoService.userLogin(username, (new MD5().getMD5(pwd)));
		if (user != null) {
			request.getSession().setAttribute("loginUser", user);
			ResponseUtils.renderText(response, "1");
		} else {
			ResponseUtils.renderText(response, "密码不正确");
		}
		return null;
	}
	
	
	/**
	 * 显示登陆页面
	 * @author yezhenchi
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "method=view")
	public String viewLogin(HttpServletRequest request){		
		return "login";
	}
	
	/**
	 * 登录主页
	 * @author yezhenchi
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "method=loginMain")
	public  ModelAndView loginMainPage( HttpServletRequest request){	
		HttpSession session = request.getSession();
		Userinfo userinfo = (Userinfo)session.getAttribute("loginUser");
		System.out.println("登录 主页啦########");
		System.out.println( userinfo.getUseremail());
		request.setAttribute("tag", userinfo.getType());
//		return "test";
		ModelAndView mav = new ModelAndView("redirect:/index.do?type=1&pageNo=0");
//		ModelAndView mav = new ModelAndView("test");
		return mav;
	}
	
	/**
	 * 退出
	 * 
	 * @author Warlock叶
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(params = "method=loginOut")
	public ModelAndView loginOutStat(HttpServletRequest request,
			HttpServletResponse response) {
		request.getSession().removeAttribute("loginUser");
		ModelAndView mav = new ModelAndView("redirect:/index.do?type=1&pageNo=0");
		return mav;
	}
}
